/**
 * 统一日志系统
 * 提供结构化日志、日志级别、性能监控功能
 */

const LOG_LEVELS = {
  DEBUG: 0,
  INFO: 1,
  WARN: 2,
  ERROR: 3,
  NONE: 4
}

class Logger {
  constructor() {
    this.level = process.env.NODE_ENV === 'production' ? LOG_LEVELS.INFO : LOG_LEVELS.DEBUG
    this.performanceMetrics = new Map()
  }

  /**
   * 设置日志级别
   * @param {string} level - DEBUG, INFO, WARN, ERROR, NONE
   */
  setLevel(level) {
    if (LOG_LEVELS[level] !== undefined) {
      this.level = LOG_LEVELS[level]
    }
  }

  /**
   * 格式化日志输出
   * @private
   */
  _formatMessage(level, category, message, data = null) {
    const timestamp = new Date().toISOString()
    const logObject = {
      timestamp,
      level,
      category,
      message
    }

    if (data) {
      logObject.data = data
    }

    return logObject
  }

  /**
   * 输出日志
   * @private
   */
  _log(level, levelName, category, message, data) {
    if (this.level > level) {
      return
    }

    const logObject = this._formatMessage(levelName, category, message, data)
    const consoleMethod = level >= LOG_LEVELS.ERROR ? 'error' :
                         level >= LOG_LEVELS.WARN ? 'warn' :
                         level >= LOG_LEVELS.INFO ? 'info' : 'log'

    console[consoleMethod](`[${logObject.timestamp}] [${levelName}] [${category}]`, message, data || '')
  }

  /**
   * DEBUG 级别日志
   */
  debug(category, message, data) {
    this._log(LOG_LEVELS.DEBUG, 'DEBUG', category, message, data)
  }

  /**
   * INFO 级别日志
   */
  info(category, message, data) {
    this._log(LOG_LEVELS.INFO, 'INFO', category, message, data)
  }

  /**
   * WARN 级别日志
   */
  warn(category, message, data) {
    this._log(LOG_LEVELS.WARN, 'WARN', category, message, data)
  }

  /**
   * ERROR 级别日志
   */
  error(category, message, error) {
    const errorData = error ? {
      message: error.message,
      stack: error.stack,
      code: error.code,
      ...(error.response && {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data
      })
    } : null

    this._log(LOG_LEVELS.ERROR, 'ERROR', category, message, errorData)
  }

  /**
   * 开始性能监控
   * @param {string} operationId - 操作标识
   */
  startPerformance(operationId) {
    this.performanceMetrics.set(operationId, {
      startTime: performance.now(),
      startMemory: performance.memory ? performance.memory.usedJSHeapSize : null
    })
    this.debug('PERFORMANCE', `Started: ${operationId}`)
  }

  /**
   * 结束性能监控并记录
   * @param {string} operationId - 操作标识
   * @param {object} metadata - 额外元数据
   */
  endPerformance(operationId, metadata = {}) {
    const metrics = this.performanceMetrics.get(operationId)
    if (!metrics) {
      this.warn('PERFORMANCE', `No start metric found for: ${operationId}`)
      return null
    }

    const endTime = performance.now()
    const duration = endTime - metrics.startTime
    const endMemory = performance.memory ? performance.memory.usedJSHeapSize : null

    const result = {
      operationId,
      duration: `${duration.toFixed(2)}ms`,
      ...metadata
    }

    if (metrics.startMemory && endMemory) {
      result.memoryDelta = `${((endMemory - metrics.startMemory) / 1024 / 1024).toFixed(2)}MB`
    }

    this.info('PERFORMANCE', `Completed: ${operationId}`, result)
    this.performanceMetrics.delete(operationId)

    return result
  }

  /**
   * 记录查询性能
   * @param {string} queryType - 查询类型 (InfluxQL/Flux)
   * @param {string} query - 查询语句
   * @param {number} rowCount - 返回行数
   * @param {number} duration - 执行时间(ms)
   */
  logQuery(queryType, query, rowCount, duration) {
    const queryPreview = query.length > 100 ? query.substring(0, 100) + '...' : query
    this.info('QUERY', `${queryType} query completed`, {
      queryPreview,
      rowCount,
      duration: `${duration.toFixed(2)}ms`,
      avgTimePerRow: rowCount > 0 ? `${(duration / rowCount).toFixed(3)}ms` : 'N/A'
    })
  }

  /**
   * 记录 API 请求
   * @param {string} method - HTTP 方法
   * @param {string} url - 请求 URL
   * @param {number} status - 响应状态码
   * @param {number} duration - 请求时长(ms)
   */
  logApiRequest(method, url, status, duration) {
    const logMethod = status >= 400 ? 'error' : status >= 300 ? 'warn' : 'debug'
    this[logMethod]('API', `${method} ${url}`, {
      status,
      duration: `${duration.toFixed(2)}ms`
    })
  }

  /**
   * 记录缓存操作
   * @param {string} operation - 操作类型 (HIT/MISS/SET/CLEAR)
   * @param {string} key - 缓存键
   * @param {object} metadata - 额外信息
   */
  logCache(operation, key, metadata = {}) {
    this.debug('CACHE', `${operation}: ${key}`, metadata)
  }
}

export default new Logger()
